<template>
	<div class="login-box">
		<h1 class="login_title">后台管理系统</h1>
		<el-form
			ref="ruleFormRef"
			style="max-width: 600px"
			:model="ruleForm"
			:rules="rules"
			label-width="auto"
			class="demo-ruleForm"
			status-icon
		>
			<el-form-item label="账号" prop="userName">
				<el-input v-model="ruleForm.userName"></el-input>
			</el-form-item>
			<el-form-item label="密码" prop="password">
				<el-input v-model="ruleForm.password" show-password></el-input>
			</el-form-item>
			<el-form-item>
				<div class="btn_group">
					<el-button type="primary" @click="submitForm(ruleFormRef)">
						登录
					</el-button>
					<el-button @click="resetForm(ruleFormRef)">重置</el-button>
				</div>
			</el-form-item>
		</el-form>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { RuleForm } from '../type/login'
import { login } from '../request/api'
import { useRouter } from 'vue-router'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

const ruleForm = reactive<RuleForm>({
	userName: '',
	password: '',
})

const rules = reactive<FormRules<RuleForm>>({
	userName: [
		{
			required: true,
			min: 3,
			max: 10,
			message: '请输入账号',
			trigger: 'blur',
		},
	],
	password: [
		{
			required: true,
			min: 3,
			max: 10,
			message: '请输入密码',
			trigger: 'blur',
		},
	],
})

const ruleFormRef = ref<FormInstance>() // 泛型

const router = useRouter() // 相当于 $router

const submitForm = async (formEl: FormInstance | undefined) => {
	console.log('formEl-->', formEl)

	if (!formEl) return
	await formEl.validate((valid, fields) => {
		console.log('ruleForm-->', ruleForm)

		if (valid) {
			console.log('submit!')
			// login(ruleForm).then((res) => {
			// 	// 账号密码：admin 123456
			// 	// 1、保存 token
			// 	// 2、保存用户信息
			// 	// 跳转页面
			// })
			localStorage.setItem('token', '123456')
			router.push('/')
		} else {
			console.log('error submit!', fields)
		}
	})
}

const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.resetFields()
}
</script>

<style scoped lang="scss">
.login-box {
	width: 100%;
	height: 100%;
	background: url('../assets/bg2.jpg') no-repeat;
	background-size: 100% 100%;
	color: #eee;
	text-align: center;
	.login_title {
		position: absolute;
		top: 30%;
		left: 50%;
		transform: translate(-50%);
	}
	.demo-ruleForm {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%);
		background-color: #eee;
		padding: 30px 20px 20px;
		border-radius: 20px;
		width: 450px;
		.btn_group {
			margin: 0 auto;
		}
	}
}
</style>
